package com.jy.datapipeline.importserver.support;

import cn.hutool.core.util.ObjectUtil;
import com.jy.datapipeline.common.constants.PrefixConstants;
import com.jy.datapipeline.importserver.common.enums.impl.TaskStatusEnum;
import com.jy.datapipeline.common.exception.GlobalException;
import com.jy.datapipeline.common.util.StringUtil;
import com.jy.datapipeline.common.vo.ReturnVo;
import com.jy.datapipeline.importserver.entity.ImportSubtask;
import com.jy.datapipeline.importserver.entity.ImportTask;
import com.jy.datapipeline.importserver.entity.ImportTaskLog;
import com.jy.datapipeline.importserver.handler.ScheduleTaskUpdStatusHandler;
import com.jy.datapipeline.importserver.service.ImportSubTaskService;
import com.jy.datapipeline.importserver.service.ImportTaskLogService;
import com.jy.datapipeline.importserver.service.ImportTaskService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @类名 MessageHandler
 * @描述 TODO
 * @作者 白条君
 * @创建日期 2023/4/27 14:27
 * @版本 1.0
 */
@Slf4j
@Component
public class MessageSupport {

    @Resource
    private ImportSubTaskService importSubTaskService;

    @Resource
    private Scheduler scheduler;

    @Resource
    private ImportTaskService importTaskService;

    @Resource
    private ImportTaskLogService importTaskLogService;

    public synchronized ReturnVo sendNotStartSubtasks() throws GlobalException {
        String notStartTaskStatus = String.valueOf(TaskStatusEnum.NOT_START.getCode());
        List<ImportSubtask> importSubTasks;
        importSubTasks = importSubTaskService.queryNotStartSubtasks(notStartTaskStatus);
        Set<Long> ids = importSubTasks.stream().map(ImportSubtask::getId).collect(Collectors.toSet());
        this.modifySubTaskStatus(ids, String.valueOf(TaskStatusEnum.RUNNING.getCode()));
        return ReturnVo.ok().put(importSubTasks);
    }

    public ReturnVo returnFailStartSubtasks(Long id) {
        List<ImportSubtask> importSubTasks = importSubTaskService.querySubtasksById(id);
//        Set<String> subtaskIds = importSubTasks.stream().map(ImportSubtask::getSubtaskId).collect(Collectors.toSet());
//        List<String> fileNames = importTaskLogService.queryTaskLogFileNames(subtaskIds, ExpConstants.DAT_FILE_NOT_EXISTS_EXP);
        return ReturnVo.ok().put(importSubTasks);
    }

    //更新子任务执行状态为正在执行
    public void modifySubTaskStatus(Set<Long> ids, String status) throws GlobalException {
        if (ObjectUtil.isNotNull(ids) && ids.size() > 0) {
            List<ImportSubtask> importSubTaskList = new ArrayList<>();
            ImportSubtask importSubTask;
            for (Long id : ids) {
                importSubTask = new ImportSubtask();
                importSubTask.setId(id);
                importSubTask.setSubtaskStatus(status);
                importSubTask.setUpdatetime(new Date());
                importSubTask.setStartTime(new Date());
                importSubTaskList.add(importSubTask);
            }
            importSubTaskService.modifySubTasksStatus(importSubTaskList);
        }
    }

    public void modifyTaskStatus(long id, String status) throws GlobalException {
        //通过subtask的id获取taskid
        ImportTask importTask = new ImportTask();
        importTask.setTaskStatus(status);
        importTask.setUpdateTime(new Date());
        String taskId = importSubTaskService.queryTaskIdBySubtaskId(id);
        importTask.setTaskId(taskId);
        importTaskService.modifyTaskByTaskId(importTask);
    }

    public void createTaskLog(ImportTaskLog importTaskLog) throws GlobalException {
        importTaskLogService.addImportTaskLog(importTaskLog);
    }

    public void updTaskStatus(long id) throws SchedulerException {
        String taskId = importSubTaskService.queryTaskIdBySubtaskId(id);

        String jobIdentity = StringUtil.concat(new StringBuffer(), PrefixConstants.JOB_UPD_TASK_STATUS, "_", taskId);

        if (!scheduler.checkExists(JobKey.jobKey(jobIdentity))) {
            JobDetail jobDetail = JobBuilder.newJob(ScheduleTaskUpdStatusHandler.class).withIdentity(jobIdentity).build();
            JobDataMap jobDataMap = jobDetail.getJobDataMap();
            jobDataMap.put("taskId", taskId);
            jobDataMap.put("jobIdentity", jobIdentity);

            SimpleScheduleBuilder simpleScheduleBuilder = SimpleScheduleBuilder
                    .simpleSchedule()
                    .repeatForever()
                    .withIntervalInSeconds(20);

            String triggerIdentity = StringUtil.concat(new StringBuffer(), PrefixConstants.TRIGGER_UPD_TASK_STATUS, "_", taskId);
            Trigger trigger = TriggerBuilder.newTrigger()
                    .withSchedule(simpleScheduleBuilder)
                    .withIdentity(triggerIdentity)
                    .build();

            scheduler.scheduleJob(jobDetail, trigger);
        }
    }
}
